package cn.smbms.controller.user;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.commons.io.FilenameUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;

import cn.smbms.pojo.Role;
import cn.smbms.pojo.User;
import cn.smbms.service.role.RoleService;
import cn.smbms.service.role.RoleServiceImpl;
import cn.smbms.service.user.UserService;
import cn.smbms.service.user.UserServiceImpl;
import cn.smbms.tools.Constants;
import cn.smbms.tools.PageSupport;

@Controller
@RequestMapping("/user")
public class UserController extends BaseController{
	private Logger logger = Logger.getLogger(UserController.class);

	private ArrayList<User> userList = new ArrayList<User>();
	
	private ArrayList<User> queryUserList= new ArrayList<User>();

	public UserController() {

		try {
			userList.add(new User(1, "test001", "赵用户001", "1111", 1,
					new SimpleDateFormat("yyyy-MM-dd").parse("1991-1-1"),
					"13778900987", "北京市海淀区", 1, 1, new Date(), 1, new Date(),
					19, "学生"));
			userList.add(new User(2, "test002", "测试用户002", "1111", 1,
					new SimpleDateFormat("yyyy-MM-dd").parse("1991-1-1"),
					"13778900987", "北京市海淀区", 1, 1, new Date(), 1, new Date(),
					19, "学生"));
			userList.add(new User(3, "test003", "测试用户003", "1111", 1,
					new SimpleDateFormat("yyyy-MM-dd").parse("1991-1-1"),
					"13778900987", "北京市海淀区", 1, 1, new Date(), 1, new Date(),
					19, "学生"));
			userList.add(new User(4, "test004", "测试用户004", "1111", 1,
					new SimpleDateFormat("yyyy-MM-dd").parse("1991-1-1"),
					"13778900987", "北京市海淀区", 1, 1, new Date(), 1, new Date(),
					19, "学生"));
			userList.add(new User(5, "test005", "测试用户005", "1111", 1,
					new SimpleDateFormat("yyyy-MM-dd").parse("1991-1-1"),
					"13778900987", "北京市海淀区", 1, 1, new Date(), 1, new Date(),
					19, "学生"));
			
		} catch (ParseException e) {
			e.printStackTrace();
		}
	}
//	@RequestMapping(value="/list",method=RequestMethod.GET)
//	public String list(Model model){
//		logger.debug("无查询条件下，获取userlist=====================");
//		model.addAttribute("queryUserList",userList);
//		return "user/userlist";
//	}
	
	@RequestMapping(value="/list2",method=RequestMethod.GET)
	public String getUserListByuserName(@RequestParam(value="userName",required=false)String userName,Model model){
		logger.info("查询条件：userName-------getUserListByuserName------------"+userName+",获取useList====");
		if (userName!=null && !userName.equals("")) {
			for (User user : userList) {
				if (user.getUserName().indexOf(userName)!=-1) {
					queryUserList.add(user);
				}
			}
			model.addAttribute("queryUserList", queryUserList);
		}else{
			model.addAttribute("queryUserList", userList);
		}
		
		
		return "user/userlist2";
		
	}
	
	
	//跳转到登录页
	@RequestMapping(value="/login.html")
	public String login(){
		logger.debug("userController------------------login-------------");
		return "login";
	}
	
	@Resource
	private UserService userService;
	@Resource
	private RoleService roleService;
	//实现登录
	@RequestMapping(value="/doLogin.html",method=RequestMethod.GET)
	public String doLogin(@RequestParam String userCode,@RequestParam String userPassword,HttpSession session,HttpServletRequest request) throws Exception{
		logger.debug("==========doLogin=====================");
		User user=userService.login(userCode, userPassword);
		logger.debug("==========doLogin======user==============="+(user!=null));
		if (null!=user) {
			session.setAttribute(cn.smbms.tools.Constants.USER_SESSION, user);
			
			return "redirect:/user/main.html";
		} else {
			request.setAttribute("error", "用户名或密码不正确");
			return "login";
		}
	}
	
	@RequestMapping(value="/main.html")
	public String main(HttpSession session){
		if (session.getAttribute(cn.smbms.tools.Constants.USER_SESSION)==null) {
			return "redirect:/user/login.html";
		}
		return "frame";
	}
	
	
	@RequestMapping(value="exlogin.html",method=RequestMethod.GET)
	public String exLogin(@RequestParam String userCode,@RequestParam String userPassword) throws Exception{
		logger.debug("&&&&&&&&&&------exLogin------&&&&&&&&&&&&&");
		User user=userService.login(userCode, userPassword);
		if (null==user) {
			throw new RuntimeException("用户编码或用户密码不正确");
		}
		return "redirect:/user/main.html";
	}
	
//	@ExceptionHandler(value={RuntimeException.class})
//	public String handlerException(RuntimeException e,HttpServletRequest req){
//		req.setAttribute("e", e);
//		return "error";
//	}
	
	
	@RequestMapping("/userlist.html")
	public String getUserList(Model model,@RequestParam(value="queryname",required=false) String queryUserName,@RequestParam(value="queryUserRole",required=false)String queryUserRole,@RequestParam(value="pageIndex",required=false)String pageIndex){
		
		
		int queryUserRole_ = 0;
		UserService userService = new UserServiceImpl();
		List<User> userList = null;
		//设置页面容量
    	int pageSize = Constants.pageSize;
    	//当前页码
    	int currentPageNo = 1;
		/**
		 * http://localhost:8090/SMBMS/userlist.do
		 * ----queryUserName --NULL
		 * http://localhost:8090/SMBMS/userlist.do?queryname=
		 * --queryUserName ---""
		 */
		System.out.println("queryUserName servlet--------"+queryUserName);  
		System.out.println("queryUserRole servlet--------"+queryUserRole);  
		System.out.println("query pageIndex--------- > " + pageIndex);
		if(queryUserName == null){
			queryUserName = "";
		}
		if(queryUserRole != null && !queryUserRole.equals("")){
			queryUserRole_ = Integer.parseInt(queryUserRole);
		}
		
    	if(pageIndex != null){
    		try{
    			currentPageNo = Integer.valueOf(pageIndex);
    		}catch(NumberFormatException e){
//    			response.sendRedirect("error.jsp");
    			return "redirect:/user/syserror.html";
    		}
    	}	
    	//总数量（表）	
    	int totalCount	= userService.getUserCount(queryUserName,queryUserRole_);
    	//总页数
    	PageSupport pages=new PageSupport();
    	pages.setCurrentPageNo(currentPageNo);
    	pages.setPageSize(pageSize);
    	pages.setTotalCount(totalCount);
    	
    	int totalPageCount = pages.getTotalPageCount();
    	
    	//控制首页和尾页
    	if(currentPageNo < 1){
    		currentPageNo = 1;
    	}else if(currentPageNo > totalPageCount){
    		currentPageNo = totalPageCount;
    	}
		
		
		userList = userService.getUserList(queryUserName,queryUserRole_,currentPageNo, pageSize);
		model.addAttribute("userList", userList);
		List<Role> roleList = null;
		RoleService roleService = new RoleServiceImpl();
		roleList = roleService.getRoleList();
		model.addAttribute("roleList", roleList);
		model.addAttribute("queryUserName", queryUserName);
		model.addAttribute("queryUserRole_", queryUserRole_);
		model.addAttribute("currentPageNo", currentPageNo);
		model.addAttribute("pageSize", pageSize);
		return "user/userlist";
	}
	
	//增加用户的处理
	@RequestMapping(value="/useradd.html",method=RequestMethod.GET)
	public String addUser(@ModelAttribute("user") User user ){
		
		return "user/useradd";
	}
	
	//保存新增用户信息
	@RequestMapping(value="/addsave.html",method=RequestMethod.POST)
	public String addUserSave(User user,HttpSession session){
		user.setCreatedBy(((User)session.getAttribute(Constants.USER_SESSION)).getId());
		user.setCreationDate(new Date());
		if (userService.add(user)) {
			return "redirect:/user/userlist.html";
		}
		return "user/useradd";
	}
	
	//@ModelAttribute注解，即将方法入参对象User添加到模型中，再根据HTTP请求消息进一步填充覆盖User对象
	@RequestMapping(value="/add.html",method=RequestMethod.GET)
	public String add(@ModelAttribute("user") User user){
		logger.debug("===========/add.html=============add===========");
		return "user/useradd";
	}
	
	
	//@Valid注解，调用校验框架根据注解声明的校验规则实施校验，校验的结果存入紧跟在后面的入参中，所以后面必须紧跟着BingingResult或者Error类型
	@RequestMapping(value="/add.html",method=RequestMethod.POST)
//	public String addSave(@Valid User user,BindingResult result,HttpSession session,HttpServletRequest request,@RequestParam(value="idPicPath",required=false)MultipartFile attach){
	public String addSave(@Valid User user,BindingResult result,HttpSession session,HttpServletRequest request,@RequestParam(value="attachs",required=false)MultipartFile[] attachs){
		logger.debug("===========/add.html=============addSave===========");
		
		
		String idPicPath=null;
		String workPicPath=null;
		String errorInfo=null;
		boolean flag=true;
		
		//定义上传目标路径
		//File.separator:windows,linux自适应路径分隔符
		String path=request.getSession().getServletContext().getRealPath("statics"+File.separator+"uploadfiles");
		
		for (int i = 0; i < attachs.length; i++) {
			MultipartFile attach=attachs[i];
			
			//判断文件是否为空
			if (!attach.isEmpty()) {
				
				if (i==0) {
					errorInfo="uploadFileError";
				} else {
					errorInfo="uploadWpError";
				}
				
				logger.debug("=========upload=================path================="+path);
				//获取原文件名
				String oldFileName=attach.getOriginalFilename();  //原文件名
				logger.debug("=====================oldFileName======="+oldFileName);
				//原文件后缀     用于判断
				String prefix=FilenameUtils.getExtension(oldFileName);
				logger.debug("=====================prefix======="+prefix);
				//文件大小判断，不得超过规定的大小
				int filesize=500000;
				logger.debug("=========uploadFile  size======="+attach.getSize());
				if (attach.getSize()>filesize) {
					request.setAttribute("uploadFileError", "上传文件大小不得超过500kb");
					return "user/useradd";
				}else if(prefix.equalsIgnoreCase("jpg")||
						prefix.equalsIgnoreCase("png")||
						prefix.equalsIgnoreCase("jpeg")||
						prefix.equalsIgnoreCase("pneg")){
					String fileName=System.currentTimeMillis()+new Random().nextInt(100000)+"_Personal.jpg";
					logger.debug("===========fileName==========="+fileName);
					File targetFile=new File(path,fileName);
					if (!targetFile.exists()) {
						targetFile.mkdirs();
					}
					
					//保存
					try {
						//将文件存储到服务器上
						attach.transferTo(targetFile);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						request.setAttribute(errorInfo, "* 上传失败");
						flag=false;
					} 
					if (i==0) {
						idPicPath=path+File.separator+fileName;
					} else if(i==1){
						workPicPath=path+File.separator+fileName;
					}
					
					logger.debug("======idPicPath============="+idPicPath);
					logger.debug("======workPicPath============="+workPicPath);
				}else {
					request.setAttribute(errorInfo, "上传图片格式不正确");
					flag=false;
				}
				
			}
		}
		
		if (flag) {
			user.setCreatedBy(((User)session.getAttribute(Constants.USER_SESSION)).getId());
			user.setCreationDate(new Date());
			//设置ipPicPath属性
			user.setIdPicPath(idPicPath);
			//设置workPicPath属性
			user.setWorkPicPath(workPicPath);
			if (userService.add(user)) {
				return "redirect:/user/userlist.html";
			}
		}
		return "user/useradd";
	}
	
	
	
	@RequestMapping(value="/usermodify.html",method=RequestMethod.GET)
	public String getUserById(@RequestParam String uid,Model model){
		logger.debug("===========getUserById==================="+uid);
		
		User user=userService.getUserById(uid);
		model.addAttribute(user);
		return "user/usermodify";
	}
	@RequestMapping(value="/usermodifysave.html",method=RequestMethod.POST)
	public String modifyUserSave(User user,HttpSession session){
		logger.debug("========modifyUserSave=============================="+user.getId());
		user.setModifyBy(((User)session.getAttribute(Constants.USER_SESSION)).getId());
		user.setModifyDate(new Date());
		if (userService.modify(user)) {
			return "redirect:/user/userlist.html";
		}
		return "user/usermodify";
	}
	
	
	//rest风格，表属性状态转移。
	//@PathVariable注解，可以将URL中的｛**｝占位符参数绑定到控制器处理方法的入参中，即：将URL中的id绑定到String类型的id入参中
	@RequestMapping(value="/view/{id}",method=RequestMethod.GET)
	public String view(@PathVariable String id,Model model){
		logger.debug("========view===============");
		User user=userService.getUserById(id);
		model.addAttribute(user);
		return "user/userview";
	}
	
	//userCode是否存在的验证
	@RequestMapping(value="/userCodeexist.html")
	@ResponseBody     //将处理方法的返回结果直接写入HTTP Response Body（Response对象的body数据区）中
	public Object getUserCodeIsExist(@RequestParam String userCode){
		logger.debug("========getUserCodeIsExist===userCode=============="+userCode);
		HashMap<String, String> resultMap=new HashMap<String,String>();
		if (StringUtils.isEmpty(userCode)) {
			resultMap.put("userCode", "exist");
		} else {
			User user=userService.selectUserCodeExist(userCode);
			if (null!=user) {
				resultMap.put("userCode", "exist");
			}else{
				resultMap.put("userCode", "noexist");
			}
		}
		
		return JSONArray.toJSONString(resultMap);
	}
	
	@RequestMapping(value="/view",method=RequestMethod.GET)
	@ResponseBody
	public Object view(@RequestParam String id){
		logger.debug("=========view-----id=============="+id);
		String cjson="";
		User user=new User();
		if (null==id||"".equals(id)) {
			return "nodata";
		} else {
			try {
				user=userService.getUserById(id);
//				cjson=JSON.toJSONString(user);
				logger.debug("=========cjson============"+cjson);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return "failed";
			}
		}
		
//		return cjson;
		return user;
	}
	
}
